﻿using SqlSugar;
using System;
using GXWA_DATA.Config;
using MappingTable = GXWA_DATA.Config.MappingTable;

namespace GXWA_DATA.Utils
{
    class SqlSugarConfig
    {
        private static string cpuId = MappingTable.DeviceIdentifier();

        private static string passWord = MappingTable.GetDataBasePasswordByCpuId(cpuId);

        // 修改后的连接字符串
        private static string connectionString =
        $"Server=127.0.0.1;Port=3306;User Id=root;Password={passWord};Database=gxwa2501_line;" +
        "Pooling=true;Maximum Pool Size=1000;SslMode=Required;AllowPublicKeyRetrieval=true;";

        // 单例实例
        private static SqlSugarClient _dbInstance;
        private static readonly object _lock = new object();

        // 单例属性
        public static SqlSugarClient Db
        {
            get
            {
                if (_dbInstance == null)
                {
                    lock (_lock)
                    {
                        if (_dbInstance == null)
                        {
                            _dbInstance = new SqlSugarClient(new ConnectionConfig()
                            {
                                ConnectionString = connectionString,
                                DbType = DbType.MySql,
                                IsAutoCloseConnection = true,
                                InitKeyType = InitKeyType.Attribute
                            });

                            // 可选：配置SQL执行事件（用于调试和日志记录）
                            _dbInstance.Aop.OnLogExecuting = (sql, pars) =>
                            {
                                // 记录SQL语句到日志
                                Console.WriteLine($"SQL: {sql}");
                            };
                        }
                    }
                }
                return _dbInstance;
            }
        }

        // 提供静态方法释放资源（在应用程序退出时调用）
        public static void Dispose()
        {
            lock (_lock)
            {
                _dbInstance?.Dispose();
                _dbInstance = null;
            }
        }
    }
}